package com.zy.cat.common.utils;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.JdException;
import com.zy.cat.entity.jd.JDGoods;
import com.zy.cat.entity.jd.JDJFGoods;
import com.zy.cat.entity.mall.resp.TKSelectionResp;
import com.zy.cat.entity.resp.Pages;
import com.zy.cat.entity.resp.ResultPage;
import com.zy.cat.entity.tb.resp.TKMaterialResp;

import jd.union.open.category.goods.get.request.CategoryReq;
import jd.union.open.category.goods.get.request.UnionOpenCategoryGoodsGetRequest;
import jd.union.open.category.goods.get.response.UnionOpenCategoryGoodsGetResponse;
import jd.union.open.goods.bigfield.query.request.BigFieldGoodsReq;
import jd.union.open.goods.bigfield.query.request.UnionOpenGoodsBigfieldQueryRequest;
import jd.union.open.goods.bigfield.query.response.UnionOpenGoodsBigfieldQueryResponse;
import jd.union.open.goods.jingfen.query.request.JFGoodsReq;
import jd.union.open.goods.jingfen.query.request.UnionOpenGoodsJingfenQueryRequest;
import jd.union.open.goods.jingfen.query.response.UnionOpenGoodsJingfenQueryResponse;
import jd.union.open.goods.promotiongoodsinfo.query.request.UnionOpenGoodsPromotiongoodsinfoQueryRequest;
import jd.union.open.goods.promotiongoodsinfo.query.response.UnionOpenGoodsPromotiongoodsinfoQueryResponse;
import jd.union.open.goods.query.request.GoodsReq;
import jd.union.open.goods.query.request.UnionOpenGoodsQueryRequest;
import jd.union.open.goods.query.response.GoodsResp;
import jd.union.open.goods.query.response.UnionOpenGoodsQueryResponse;
import jd.union.open.promotion.bysubunionid.get.request.UnionOpenPromotionBysubunionidGetRequest;
import jd.union.open.promotion.bysubunionid.get.response.UnionOpenPromotionBysubunionidGetResponse;
import jd.union.open.promotion.common.get.request.PromotionCodeReq;
import jd.union.open.promotion.common.get.request.UnionOpenPromotionCommonGetRequest;
import jd.union.open.promotion.common.get.response.UnionOpenPromotionCommonGetResponse;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @info 京东api
 * @author Link
 * @date 2019-08-14 14:07
 */
@Slf4j
public class JDAPI {

	public static final int DEFAULT_TYPE = 10;
	private String SERVER_URL = "https://router.jd.com/api";
	private String appKey = "43b8da32748b4615689b5b6e4ded93b7";
	private String appSecret = "ed5fae41641245c9ae4cc7b84c4b2790";
	private String accessToken = "e4209eac5db9f8e2a113de67477c4c2a36e44cc9a7f303642a6e1e15aa7efb2b7462417bbf8ff262";
	private String pid = "1000288503_885987358_1869727379";
	private String siteId = "885987358";// APPID
	private long positionId = 1869727379;// 推广位ID
	private String tag = "";// 标签
	private int ctype = 0;// 账户类型0.九趣猫

	private JDAPI(String appKey, String appSecret, String pid, String accessToken, int ctype) {
		super();
		this.appKey = appKey;
		this.appSecret = appSecret;
		this.pid = pid;
		this.accessToken = accessToken;
		this.ctype = ctype;
	}

	public static void main(String[] args) {
		int stype=0;
		String sortName="price";
		if(stype==0) {
			sortName="price";
		}else if(stype==1) {
			sortName="commissionShare";
		}else if(stype==2) {
			sortName="commission";
		}else if(stype==3) {
			sortName="inOrderCount30Days";
		}else if(stype==4) {
			sortName="inOrderComm30Days";
		} 
		Object result = null;
		String stime = "", etime = TJKUtils.DateTime();
		etime = TJKUtils.parse2LocalDateTime(etime).minusDays(1).format(DateAPIUtils.FORMATTER_YYYYMMDDHHMMSS);
		stime = TJKUtils.parse2LocalDateTime(etime).minusHours(1).format(DateAPIUtils.FORMATTER_YYYYMMDDHHMMSS);
		Long cid1=737l, cid2=0l, cid3=0l;
		String mid="item.jd.com/70302050351.html";
		String cid="https://coupon.m.jd.com/coupons/show.action?linkKey=AAROH_xIpeffAs_-naABEFoeOUhRUiQDm3QJVYY1kZSLddtZTrXN0gZNKfHqLzl9xXLuBkZ8LGUg3JIyAAgV96bXeTKFhg";
// 		result = JDAPI.getInstance(0).getJingFen(1, 1, 20, "commission", "desc");
// 		result = JDAPI.getInstance(0).getGoodsQuery("女裙");
//		result = JDAPI.getInstance(0).getGoodsOrder();
// 		result = JDAPI.getInstance(0).getCats(1316, 1);
//		result = JDAPI.getInstance(0).getGoodsConvertBySbUnionid("1111111111",mid,"",0);
//		result = JDAPI.getInstance(0).getGoodsLike(1316l,null,null);
//		result = JDAPI.getInstance(0).getGoods(1, "", cid1, cid2, cid3, sortName, "desc", -1);
		result = JDAPI.getInstance(0).getGoodsInfo("60472296051");
		log.info(JSON.toJSONString(result));
	}

	/**
	 * 
	 * @author Link
	 * @date 2019-06-28 08:53
	 * @param type 账户(0.九趣猫)
	 * @return
	 */
	public static JDAPI getInstance(int type) {
		String appKey = "72a10d4086d47276ef96ffc3baa9e24b";
		String appSecret = "e8eb1c9804fd4b329eeda78929b6758c";
		String accessToken = "b57733a7028b09013f46845a67fec39554d4dcc5e4c044a99078eff130f4fb646c129f897d2078a1";
		String pid = "1002992246_4000216271_3002588888";
		return new JDAPI(appKey, appSecret, pid, accessToken, type);
	}

	/**
	 * 
	 * @info 京东联盟精选优质商品
	 * @author Link
	 * @date 2019-08-14 14:21
	 * @param eliteId   1-好券商品,2-京粉APP-jingdong.超级大卖场,3-小程序-jingdong.好券商品,4-京粉APP-jingdong.主题聚惠1-jingdong.服装运动,5-京粉APP-jingdong.主题聚惠2-jingdong.精选家电,6-京粉APP-jingdong.主题聚惠3-jingdong.超市,7-京粉APP-jingdong.主题聚惠4-jingdong.居家生活,10-9.9专区,11-品牌好货-jingdong.潮流范儿,12-品牌好货-jingdong.精致生活,13-品牌好货-jingdong.数码先锋,14-品牌好货-jingdong.品质家电,15-京仓配送,16-公众号-jingdong.好券商品,17-公众号-jingdong.9.9,18-公众号-jingdong.京东配送,22-精品库
	 * @param pageIndex 页码
	 * @param pageSize  每页数量，默认20，上限50
	 * @param sortName  排序字段(price：单价, commissionShare：佣金比例, commission：佣金，
	 *                  inOrderCount30DaysSku：sku维度30天引单量，comments：评论数，goodComments：好评数)
	 * @param sort      asc,desc升降序,默认降序
	 */
	public UnionOpenGoodsJingfenQueryResponse getJingFen(int eliteId, int pageIndex, int pageSize, String sortName,
			String sort) {
		JdClient client = new DefaultJdClient(SERVER_URL, accessToken, appKey, appSecret);

		UnionOpenGoodsJingfenQueryRequest request = new UnionOpenGoodsJingfenQueryRequest();
		JFGoodsReq goodsReq = new JFGoodsReq();
		goodsReq.setSortName(sortName);
		goodsReq.setEliteId(eliteId);
		goodsReq.setPageIndex(pageIndex);
		goodsReq.setPageSize(pageSize);
		goodsReq.setSort(sort);
		request.setGoodsReq(goodsReq);
		UnionOpenGoodsJingfenQueryResponse response = null;
		try {
			response = client.execute(request);
		} catch (JdException e) {
			log.error("-->" + e.getLocalizedMessage());
		}
		return response;
	}

	/**
	 * 
	 * @info 商品搜索
	 * @author Link
	 * @date 2020-06-29 15:22
	 * @return
	 */
	public UnionOpenGoodsQueryResponse getGoodsQuery(String query) {
		JdClient client = new DefaultJdClient(SERVER_URL, accessToken, appKey, appSecret);
		UnionOpenGoodsQueryRequest request = new UnionOpenGoodsQueryRequest();
		GoodsReq goodsReqDTO = new GoodsReq();
		goodsReqDTO.setKeyword(query);
		request.setGoodsReqDTO(goodsReqDTO);
		UnionOpenGoodsQueryResponse response = null;
		try {
			response = client.execute(request);
		} catch (JdException e) {
			log.error("-京东商品搜索信息错误-{}->{}",e.getLocalizedMessage(),JSON.toJSONString(response));
		}
		return response;
	}

	/**
	 * 获取类目信息
	 * 
	 * @info
	 * @author Link
	 * @date 2020-06-29 15:28
	 * @param parentId 父类目id(一级父类目为0)
	 * @param grade    类目级别(类目级别 0，1，2 代表一、二、三级类目)
	 * @return
	 */
	public UnionOpenCategoryGoodsGetResponse getCats(int parentId, int grade) {
		JdClient client = new DefaultJdClient(SERVER_URL, accessToken, appKey, appSecret);
		UnionOpenCategoryGoodsGetRequest request = new UnionOpenCategoryGoodsGetRequest();
		CategoryReq req = new CategoryReq();
		req.setParentId(parentId);
		req.setGrade(grade);
		request.setReq(req);
		UnionOpenCategoryGoodsGetResponse response = null;
		try {
			response = client.execute(request);
		} catch (JdException e) {
			log.error("-京东商品类目信息错误-{}->{}",e.getLocalizedMessage(),JSON.toJSONString(response));
		}
		return response;
	}

	/**
	 * 
	 * @info 商品转链(进去分推广位)
	 * @author Link
	 * @date 2020-06-29 16:23
	 * @param mid  商品详情页url
	 * @param cid  商品优惠券url
	 * @param type 九趣猫账户(0.九趣猫、1.淘淘集、2.一陶)
	 * @return
	 */
	public UnionOpenPromotionCommonGetResponse getGoodsConvert(String pid, String mid, String cid, int type) {
		String upid = "1002992246_4000216271_3002588888", tag = "";
		if (ctype == 0) {
			if (type == 0) {
				upid = "1002992246_4000216271_3002588888";
				tag = "ZY_JQM_";
			} else if (type == 1) {
				upid = "1002992246_4000216271_3002588889";
				tag = "ZY_TTJ_";
			} else if (type == 2) {
				upid = "1002992246_4000216271_3002588890";
				tag = "ZY_YT_";
			}
		}
		String siteId = upid.split("_")[1];
		long positionId = 3002588888l;
		try {
			positionId = Long.parseLong(upid.split("_")[2]);
		} catch (Exception e) {
		}
		JdClient client = new DefaultJdClient(SERVER_URL, accessToken, appKey, appSecret);
		UnionOpenPromotionCommonGetRequest request = new UnionOpenPromotionCommonGetRequest();
		PromotionCodeReq promotionCodeReq = new PromotionCodeReq();
		promotionCodeReq.setSubUnionId(pid);
		promotionCodeReq.setMaterialId(mid);
		if (StringUtils.isNotBlank(cid)) {
			promotionCodeReq.setCouponUrl(cid);
		}
		promotionCodeReq.setSiteId(siteId);
		promotionCodeReq.setPositionId(positionId);
		request.setPromotionCodeReq(promotionCodeReq);
		UnionOpenPromotionCommonGetResponse response = null;
		try {
			response = client.execute(request);
		} catch (JdException e) {
			log.error("-京东商品固定转链错误-{}->{}",e.getLocalizedMessage(),JSON.toJSONString(response));
		}
		log.info("-京东商品固定转链-->{}",JSON.toJSONString(response));
		return response;
	}
	
	/**
	 * 
	 * @info 商品自定转链（可自定义参数）
	 * @author Link
	 * @date 2020-06-29 16:23
	 * @param pid  用户自定义id
	 * @param mid  商品详情页url
	 * @param cid  商品优惠券url
	 * @param type 九趣猫账户(0.九趣猫、1.淘淘集、2.一陶)
	 * @return
	 */
	public  UnionOpenPromotionBysubunionidGetResponse getGoodsConvertBySbUnionid(String sbUnionid, String mid, String cid, int type) {
		String upid = "1002992246_4000216271_3002588888", tag = "";
		if (ctype == 0) {
			if (type == 0) {
				upid = "1002992246_4000216271_3002588888";
				tag = "ZY_JQM_";
			} else if (type == 1) {
				upid = "1002992246_4000216271_3002588889";
				tag = "ZY_TTJ_";
			} else if (type == 2) {
				upid = "1002992246_4000216271_3002588890";
				tag = "ZY_YT_";
			}
		}
		long positionId = 3002588888l;
		try {
			positionId = Long.parseLong(upid.split("_")[2]);
		} catch (Exception e) {
		}
		
		JdClient client=new DefaultJdClient(SERVER_URL,accessToken,appKey,appSecret);
		UnionOpenPromotionBysubunionidGetRequest request=new UnionOpenPromotionBysubunionidGetRequest();
		jd.union.open.promotion.bysubunionid.get.request.PromotionCodeReq promotionCodeReq=new jd.union.open.promotion.bysubunionid.get.request.PromotionCodeReq();
		
		promotionCodeReq.setSubUnionId(sbUnionid);
		promotionCodeReq.setMaterialId(mid);
		if (StringUtils.isNotBlank(cid)) {
			promotionCodeReq.setCouponUrl(cid);
		}
    	promotionCodeReq.setChainType(3);
		promotionCodeReq.setPositionId(positionId);
		request.setPromotionCodeReq(promotionCodeReq);
		UnionOpenPromotionBysubunionidGetResponse response = null;
		try {
			response = client.execute(request);
		} catch (JdException e) {
			log.error("-京东商品自定义转链错误-{}->{}",e.getLocalizedMessage(),JSON.toJSONString(response));
		}
		log.info("-京东商品自定义转链-->{}",JSON.toJSONString(response));
		return response;
	}

	/**
	 * 获取商品详细信息
	 * 
	 * @info
	 * @author Link
	 * @date 2020-06-30 16:58
	 * @param skuIds
	 * @return
	 */
	public UnionOpenGoodsPromotiongoodsinfoQueryResponse  getGoodsInfo(String skuIds) {
		JdClient client = new DefaultJdClient(SERVER_URL, accessToken, appKey, appSecret);
		UnionOpenGoodsPromotiongoodsinfoQueryRequest request=new UnionOpenGoodsPromotiongoodsinfoQueryRequest();
		request.setSkuIds(skuIds);
		UnionOpenGoodsPromotiongoodsinfoQueryResponse response = null;
		try {
			response = client.execute(request);
			log.info(JSON.toJSONString(response));
		} catch (JdException e) {
			log.error("-京东商品信息错误-{}->{}",e.getLocalizedMessage(),JSON.toJSONString(response));
		}
		return response;
	}

	public UnionOpenGoodsQueryResponse getGoods(int pageIndex, String keyWords, Long cid1, Long cid2, Long cid3, String sortName,
			String sort,int isCoupon,String owner) {
		pageIndex = pageIndex < 0 ? 1 : pageIndex;
		JdClient client = new DefaultJdClient(SERVER_URL, accessToken, appKey, appSecret);
		UnionOpenGoodsQueryRequest request = new UnionOpenGoodsQueryRequest();
		
		GoodsReq goodsReqDTO = new GoodsReq();
		
		if(StringUtils.isNotBlank(sortName)) {
			goodsReqDTO.setSortName(sortName);
		}
		if(StringUtils.isNotBlank(sort)) {
			goodsReqDTO.setSort(sort);
		}
		goodsReqDTO.setPageIndex(pageIndex);
		goodsReqDTO.setPageSize(30);
		if (StringUtils.isNotBlank(keyWords)) {
			goodsReqDTO.setKeyword(keyWords);
		}
		if(isCoupon>=0) {
			goodsReqDTO.setIsCoupon(isCoupon);
		}
		if (cid1 != null&&cid1>0) {
			goodsReqDTO.setCid1(cid1);
		}
		if (cid2 != null&&cid2>0) {
			goodsReqDTO.setCid2(cid2);
		}
		if (cid3 != null&&cid3>0) {
			goodsReqDTO.setCid3(cid3);
		}
		goodsReqDTO.setOwner(owner);
		request.setGoodsReqDTO(goodsReqDTO);
		UnionOpenGoodsQueryResponse response = null;
		try {
			response = client.execute(request);
		} catch (JdException e) {
			log.error("-京东商品列表信息错误-{}->{}",e.getLocalizedMessage(),JSON.toJSONString(response));
		}
		log.info("-京东商品列表信息->"+JSON.toJSONString(response));
		return response;
	}

	/**
	 * 根据skuid获取类似商品
	 * @info 
	 * @author Link
	 * @date 2020-07-01 08:56
	 * @param skuids   5225346,7275691
	 * @return
	 */
	public UnionOpenGoodsQueryResponse getGoodsLike( Long cid1, Long cid2, Long cid3) {
		JdClient client = new DefaultJdClient(SERVER_URL, accessToken, appKey, appSecret);
		UnionOpenGoodsQueryRequest request = new UnionOpenGoodsQueryRequest();
		
		GoodsReq goodsReqDTO = new GoodsReq();
		goodsReqDTO.setPageIndex(1);
		goodsReqDTO.setPageSize(30);
		if (cid1 != null) {
			goodsReqDTO.setCid1(cid1);
		}
		if (cid2 != null) {
			goodsReqDTO.setCid2(cid2);
		}
		if (cid3 != null) {
			goodsReqDTO.setCid3(cid3);
		}
		request.setGoodsReqDTO(goodsReqDTO);
		UnionOpenGoodsQueryResponse response = null;
		try {
			response = client.execute(request);
		} catch (JdException e) {
			log.error("-京东相似推荐商品信息错误-{}->{}",e.getLocalizedMessage(),JSON.toJSONString(response));
		}
		log.info("-京东相似推荐商品信息->"+JSON.toJSONString(response));
		return response;
	}


	
	
	
/**
 * 获取今日推荐商品信息
 * @param pageIndex
 * @param keyWords
 * @param sortName
 * @param sort
 * @param isCoupon
 * @param owner
 * @return
 */
	public UnionOpenGoodsQueryResponse getTjGoods(int pageIndex, String keyWords,String sortName,String sort,int isCoupon,String owner) {
		pageIndex = pageIndex < 0 ? 1 : pageIndex;
		JdClient client = new DefaultJdClient(SERVER_URL, accessToken, appKey, appSecret);
		UnionOpenGoodsQueryRequest request = new UnionOpenGoodsQueryRequest();
		GoodsReq goodsReqDTO = new GoodsReq();
		if(StringUtils.isNotBlank(sortName)) {
			goodsReqDTO.setSortName(sortName);
		}
		if(StringUtils.isNotBlank(sort)) {
			goodsReqDTO.setSort(sort);
		}
		goodsReqDTO.setPageIndex(pageIndex);
		goodsReqDTO.setPageSize(30);
		if (StringUtils.isNotBlank(keyWords)) {
			goodsReqDTO.setKeyword(keyWords);
		}
		if(isCoupon>=0) {
			goodsReqDTO.setIsCoupon(isCoupon);
		}
		goodsReqDTO.setOwner(owner);
		request.setGoodsReqDTO(goodsReqDTO);
		UnionOpenGoodsQueryResponse response = null;
		try {
			response = client.execute(request);
		} catch (JdException e) {
			log.error("-京东商品列表信息错误-{}->{}",e.getLocalizedMessage(),JSON.toJSONString(response));
		}
		log.info("-京东商品列表信息->"+JSON.toJSONString(response));
		return response;
	}

	
	
	
	//	/**
//	 *  获取今日推荐商品信息
//	 * @param key
//	 * @param sex
//	 * @param pageNum
//	 * @return
//	 */
//	@SuppressWarnings("unused")
//	public ResultPage<JDGoods> getTJList(String key, Integer sex, Pages pages) {
//		// TODO Auto-generated method stub
//		UnionOpenGoodsQueryRequest request = new UnionOpenGoodsQueryRequest();
////		ResultPage<JDGoods> resultPage=getTJList(key,sex,pages);		
////		if (resultPage!=null && resultPage.getList()!=null) {
//			List<JDGoods> list = JSON.parseArray(JSON.toJSONString(request.getGoodsReqDTO()),JDGoods.class);
//			ResultPage<JDGoods> pageResult=new ResultPage<>(pages.getPageNum(), pages.getPageSize());
//			pageResult.setTotal(pageResult.getTotal());
//			pageResult.setList(list);
//			return pageResult;
////			}
//	}
	
}
